package com.grant.HelloWorld.server;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.core.client.GWT;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.geronimo.mail.util.StringBufferOutputStream;

public class SignGuestbookServlet extends HttpServlet {
	private static final Logger log = Logger
			.getLogger(SignGuestbookServlet.class.getName());
	

	@SuppressWarnings("deprecation")
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		//UserService userService = UserServiceFactory.getUserService();
		//User user = userService.getCurrentUser();
		User user = new User("wuyq@abc.com", "changyi");
		//guestbookName = req.getParameter("guestbookName");
		SimpleDateFormat formatter = new SimpleDateFormat("ddMMyy-HH:mm:ss");
		Date fileUploadDate = new Date();
		Key uploadFileKey = KeyFactory.createKey("UploadFile", formatter.format(fileUploadDate));
		//
		String content = getFileItem(req);
		Text txt = new Text(content);
		
		if (!content.equals("")){
			Entity uploadedFile = new Entity("UploadFile", uploadFileKey);
			System.out.println("uploadFileKey="+KeyFactory.keyToString(uploadFileKey));
			uploadedFile.setProperty("date", fileUploadDate);
			uploadedFile.setProperty("size", content.length());
			uploadedFile.setProperty("content", txt);
			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();
			datastore.put(uploadedFile);
		}
		
		//resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
		
		String s = searchDB();
		PrintWriter out = resp.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">\n" + "<HTML>\n"
				+ "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n"
				+ "<H1>Hello WWW</H1>\n" 
				+ (new Date()).toString()  
				+"<br/>"
				+ "uploaded file list"
				+"<br/>"
				+ s
				+"<br/>"
				+""
				+ "</BODY></HTML>");
		log("greetServer(\"\")");
	}
	
	
	private String searchDB()
	{
		String s = "";
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		//Key uploadFileKey = KeyFactory.createKey("Guestbook", guestbookName);
		// Run an ancestor query to ensure we see the most up-to-date
		// view of the Greetings belonging to the selected Guestbook.
		Query query = new Query("UploadFile").addSort("date",
				Query.SortDirection.DESCENDING);
		List<Entity> uploadedFiles = datastore.prepare(query).asList(
				FetchOptions.Builder.withLimit(5));
		if (uploadedFiles.isEmpty()) {
			s = "";
		} else {			
			for (Entity oneFile : uploadedFiles) {
				if (oneFile.getProperty("date") == null) {
					s = "";
				} else {					
					s += "<hr/>";
					s += oneFile.getProperty("date").toString();
					if (oneFile.hasProperty("size") && oneFile.getProperty("size")!=null){
						s += "<br/>";
						s += "size = " + oneFile.getProperty("size").toString();
					}
					s += "<br/>";
					//s = s+ oneFile.getProperty("content").toString();
					s += "<br/>";
					s += "<a href='/downloadFile?fileKey="
							+ KeyFactory.keyToString(oneFile.getKey()) 
							+"'>donwload the file</a>";
					s += "<br/>";					
				}
			}
		 }
		return s;
	}
	
	//http://code.google.com/p/file-upload-for-gae/source/browse/FileUploadForGAE/src/pt/atwork/mpadilha/fugae/FileUploadServlet.java
	 private String getFileItem(HttpServletRequest request){ 
		 
		 String s = "";
			// Create a factory for disk-based file items
			  MemoryFileItemFactory factory = new MemoryFileItemFactory();


			  // Create a new file upload handler
			  ServletFileUpload upload = new ServletFileUpload(factory);

			  // Parse the request
			  try {
				  GWT.log("parse ... ");System.out.println("parse ... ");
				List /* FileItem */ items = upload.parseRequest(request);
				GWT.log(String.format("items size %d", items.size()));
				System.out.println(String.format("items size %d", items.size()));
				
				@SuppressWarnings("rawtypes")
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
				    FileItem item = (FileItem) iter.next();

				    if (!item.isFormField())  {
				        s = s + processUploadedFile(item);
				    }
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			  
			  return s;
	  } 
	
	private String processUploadedFile(FileItem item){
		String s = "";
		// Process a file upload
		if (!item.isFormField()) {
			String fieldName = item.getFieldName();
			String fileName = item.getName();
			String contentType = item.getContentType();
			boolean isInMemory = item.isInMemory();
			long sizeInBytes = item.getSize();

			System.out.println("fileName=" + fileName);
			System.out
					.println("sizeInBytes" + new Long(sizeInBytes).toString());

			s = item.getString();

			try {
				// item.write(stream);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return s;
	}
}